<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use phpDocumentor\Reflection\Types\Self_;

class Article extends Model
{
    //
    const TABLE = 'article_title';
    public function addArticle()
    {
        DB::beginTransaction();
        try {
            $id = DB::table('y_article_title')->insertGetId();
            DB::insert();
        } catch (Exception $e) {
            DB::rollBack();
        }
    }

    /**获取文章标题列表
     * @param $type
     * @return \Illuminate\Support\Collection
     */
    public function getArticleTitle($type)
    {
        $list = DB::table(self::TABLE)->leftJoin('user', self::TABLE . '.user_id', '=', 'user.id')->select(self::TABLE . '.*', 'user.name')->where(self::TABLE . '.type', $type)->get();
        return $list;
    }

    /**获取文章信息
     * @param $article_title_id
     * @return \Illuminate\Support\Collection
     */
    public function getArticle($article_title_id)
    {
        $info = DB::table(self::TABLE)
            ->leftJoin('article', self::TABLE . '.acticle_id', '=', 'article.id')
            ->leftJoin('user', self::TABLE . '.user_id', '=', 'user.id')
            ->where(self::TABLE . '.id', '=', $article_title_id)
            ->select(self::TABLE . '.*', 'article.content as content_all', 'user.name')
            ->first();
        return $info;
    }

    /**阅读量
     * @param $article_title_id
     * @return int
     */
    public function updateArticle($article_title_id)
    {
        return DB::table(self::TABLE)->where('id', $article_title_id)->increment('read_num', 1);

    }

    /**更新点赞
     * @param $article_title_id
     * @return int
     */
    public function updateArticleLike($article_title_id)
    {
        return DB::table(self::TABLE)->where('id', $article_title_id)->increment('like', 1);
    }

    /**获取点击排行榜
     * @param $type
     * @return \Illuminate\Support\Collection
     */
    public function getArticleTitleTop($type)
    {
        $list = DB::table(self::TABLE)
            ->leftJoin('user', self::TABLE . '.user_id', '=', 'user.id')
            ->select(self::TABLE . '.*', 'user.name')
            ->where(self::TABLE . '.type', $type)
            ->orderByDesc(self::TABLE . '.read_num')
            ->limit(3)
            ->get();
        return $list;
    }
}
